#ifndef __COMM_HPP__
#define __COMM_HPP__

#include<iostream>
#include<string>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include"log/log.hpp"
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>

using namespace std;

const string pathname = "/root";
const int size_buffer = 4096;
const int proj_id = 0x6666;
Log log;
key_t GetKey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if(k<0)
    {
        log(FATAL,"ftok error: %s",strerror(errno));
        exit(1);
    }
    log(INFO,"ftok success,key: %d",k);
    return k;

}

int GetShareMemHelper(int flag)
{
    key_t k = GetKey();
    int shmid = shmget(k,size_buffer,flag);
    if(shmid<0)
    {
        log(FATAL,"shmget error: %s",strerror(errno));
        exit(2);
    }
    log(INFO,"shmget success,shmid: %d",shmid);
    return shmid;

}

int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}


#define FIFO_FILE "./myfifo"
#define MODE 0664

enum{
    FIFO_CREATE_ERROR= 1,
    FIFO_DELETE_ERROR= 2,
    FIFO_OPEN_ERROR= 3
};

class Init{
public:
    Init()
    {
        // 创建管道
        int n = mkfifo(FIFO_FILE,MODE);
        if(n==-1)
        {
            // printf("%d:%s\n",errno,strerror(errno));
            perror("mkfifo");
            exit(FIFO_CREATE_ERROR);
        }
    }

    ~Init()
    {
        int m = unlink(FIFO_FILE);
        if(m==-1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERROR);
        }
    }
};


#endif